<?php

namespace Frieza\Modules\CommunityMcn\Controllers;

use App\Exceptions\InputErrorException;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\CommunityMcn\Brief;
use Doraemon\model\McnUser as mMcnUser;
use Doraemon\service\CommunityMcn\AdminRole;
use Doraemon\service\CommunityMcn\Brief as sBrief;
use Doraemon\tools\Hhzurl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Frieza\Modules\Topic\Extensions\Widgets\Form;
use Illuminate\Http\Request;
use Doraemon\service\CommunityMcn\InviteMember;
use Doraemon\model\CommunityMcn\InviteMember as mInviteMember;
use Illuminate\Support\MessageBag;
use Doraemon\model\Member;
use Doraemon\model\McnUser;

class InviteMemberController extends Controller
{


    public function list(Request $request, Content $content,$briefId = 0)
    {
        $params = $request->all();
        $page = $request->input('page', 1);
        $pageSize = $request->input('pageSize', 20);
        $limit = [($page - 1) * $pageSize, $pageSize];
        $order = ['add_time' => 'DESC'];
        $where['brief_id'] = $briefId;
        if($params['uid']){
            $where['uid'] = $params['uid'];
        }
        $list = InviteMember::getListByWhere($where, $limit, $order);
        $data = self::setData($list['list'],$briefId);
        $gridModel = new pGridDataModel($data, $list['total'], ['perPage' => $pageSize]);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($briefId){
            $grid->disableExport();
            $grid->disableCreateButton();
            $grid->disableRowSelector();
            $grid->filter(function (Grid\Filter $filter){
                $filter->disableIdFilter();
                $filter->column(1/2, function ($filter) {
                    $filter->equal('uid', 'uid')->placeholder('uid');
                });
            });
            $grid->column('id')->hide();
            $grid->column('uid', 'uid');
            $grid->column('nick', '昵称');
            $grid->column('level', '商业用户等级');
            $grid->column('content_type', '内容类型');
            $grid->column('note_id', '已发布内容');
            $grid->column('data_type', '数据情况');
            $grid->header(function () use ($briefId){
                $briefInfo = sBrief::getInfoById($briefId);
                $brandList = sBrief::getBrandList();
                $briefInfo['popularize_brand_name'] = $briefInfo['brand_inner'] == 1 ?$brandList[$briefInfo['popularize_brand_id']]:$briefInfo['popularize_brand_name'];
                $url = '/admin/communityMcn/briefInfo/'.$briefId.'/read';
                $html = '<p>Brief信息：</p>';
                $html .= '订单号：'. $briefInfo['order_id'];
                $html .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Brief名称：'. $briefInfo['project_name'];
                $html .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;推广品牌：'. $briefInfo['popularize_brand_name'];
                $html .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;推广产品：'. $briefInfo['popularize_product'];
                $html .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="'.$url.'">查看详情</a>';
                return $html;
            });
            $grid->actions(function (Grid\Displayers\Actions $actions){
                $actions->disableDelete();
                $actions->disableEdit();
                $id = $actions->row->id;
                $url = '/admin/communityMcn/inviteMember/'. $id  .'/createContent';
                $actions->prepend('<a class="fa fa-indent reload-data" href="'.$url.'" >编辑内容</a><br>');
            });

        });
        return $content
            ->header('MCN邀约人员列表')
            ->breadcrumb(['text' => 'MCN邀约人员列表', 'url' => '/admin'])
            ->body($listGrid);
    }

    public static function setData($data = array(),$briefId){
        if(!$data) return [];
        $briefInfo = sBrief::getInfoById($briefId);
        $uidList = [];
        foreach ($data as $value){
            $uidList[] = $value['uid'];
        }
        //避免循环查库
        $userList = McnUser::selectByWhere(['uid'=>$uidList],['uid','level','nick']);
        $userSelect = [];
        foreach ($userList as $value){
            $userSelect[$value['uid']] = ['level' => $value['level'],'nick' => $value['nick']];
        }
        $list = [];
        foreach ($data as $key=>$value){
            $list[$key]['id'] = $value['id'];
            $list[$key]['uid'] = $value['uid'];
            $list[$key]['level'] = $userSelect[$value['uid']]['level'];
            $list[$key]['nick'] = $userSelect[$value['uid']]['nick'];
            $list[$key]['note_id'] = $value['note_id'];
            $list[$key]['content_type'] = Brief::CONTENT_TYPE_LIST[$briefInfo['content_type']];
            $list[$key]['data_type'] = '好好住';
        }
        return array_values($list);
    }

    public function create(Request $request, Content $content,$briefId = 0)
    {
        $form = new Form();
        $form->hidden('brief_id')->default($briefId);
        $form->textarea('text', '输入KOL UID')->rows(10)->help('请填写uid，以英文逗号（,）分隔。例：123,456');
        $form->confirm('确认提交');
        $form->action('/admin/communityMcn/inviteMember/save');
        return $content
            ->header('添加kol')
            ->breadcrumb(
                [
                    'text' => '',
                    'url'  => ''
                ],
                ['text' => "添加kol"]
            )
            ->body($form);
    }

    public function save(Request $request)
    {
        $param = $request->all();
        $briefId = $param['brief_id'];
        $uidString = $param['text'];
        $uidsList = explode(',',$uidString);
        $uidsList = array_unique($uidsList);
        $count = count($uidsList);
        if($uidsList){
            $dbCount = Member::countUserNum(['uid' => $uidsList]);
        }
        if($count != $dbCount){
            throw new InputErrorException('存在无法识别的uid', InputErrorException::DEFAULT_CODE, 'text');
        }

        $insertData = array();
        foreach($uidsList as $value){
            $insertData[] = [
                'uid' => $value,
                'brief_id' => $briefId,
                'add_time' => time(),
                'status' => 1
            ];
        }
        $insertCount = mInviteMember::insert($insertData)->rowCount();
        if($insertCount){
            Brief::updateById($briefId,['status'=>Brief::STATUS_DISPATCH_SUCCESS,'close_time'=> Brief::DEFAULT_CLOSE_TIME]);
            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect('admin/communityMcn/inviteMember/'.$briefId.'/index')->with(compact('success'));
        }else{
            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        }

    }

    public function createContent(Content $content, Request $request, $inviteId = 0)
    {
        $isBusiness = AdminRole::isBusiness();
        //查询内容信息
        $info = InviteMember::getInfoByInviteId($inviteId);
        if (empty($info)) {
            $message = '找不到该数据';
            $error = new MessageBag([
                'title' => $message
            ]);
            return redirect("/admin/communityMcn/inviteMember/{$inviteId}/index")->with(compact('error'));
        }
        //brief数据
        $briefInfo = sBrief::getInfoById($info['brief_id']);
        if (empty($briefInfo)) {
            $message = '找不到brief数据';
            $error = new MessageBag([
                'title' => $message
            ]);
            return redirect("/admin/communityMcn/inviteMember/{$inviteId}/index")->with(compact('error'));
        }
        //用户信息
        $aInfo = mMcnUser::getInfo(['uid' => $info['uid'],'status' => 1]);
        if (empty($aInfo)) {
            $message = '找不到用户数据';
            $error = new MessageBag([
                'title' => $message
            ]);
            return redirect("/admin/communityMcn/inviteMember/{$inviteId}/index")->with(compact('error'));
        }
        $data['note_id'] = $info['note_id'];
        $data['content'] = $info['content'];
        $data['content_type_desc'] = $briefInfo['content_type_desc'];
        $data['brief_info'] = "（" . $briefInfo['order_id'] . "," . $briefInfo['project_name'] . ")";
        $data['user_info'] = "（" . $aInfo['uid'] . "," . $aInfo['nick'] . "," . $aInfo['level'] . ")";

        $form = new \Encore\Admin\Widgets\Form($data);
        $form->text('content_type_desc', '内容类型')->readonly();

        $noteId = $form->text('note_id', 'NoteId')->placeholder('请填写NoteId');
        $form->html('<span id="view" class="btn btn-sm btn-success button-1134271147">预览</span>');
        $contents = $form->textarea('content', '脚本');
        if ($isBusiness) {
            $form->disableSubmit();
            $noteId->readonly();
            $contents->readonly();
        }

        $url = Hhzurl::getDomain();
        Admin::script($this->saveScript($url));
        $form->text('user_info', '用户基础信息')->readonly();
        $form->text('brief_info', 'Brief基础信息')->readonly();
        $form->hidden('brief_id')->default($info['brief_id']);
        // 去掉`重置`按钮
        $form->disableReset();

        $form->action("/admin/communityMcn/inviteMember/{$inviteId}/addContent");

        return $content->header('')
            ->breadcrumb(['text' => '商品管理', 'url' => 'circle'], ['text' => '商品编辑'])
            ->row($form->render());
    }

    public function addContent(Content $content, Request $request, $inviteId = 0)
    {
        $data['note_id'] = $request->input('note_id', 0);
        $data['content'] = $request->input('content', 0);
        $briefId = $request->input('brief_id', 0);
        $result = InviteMember::updByInviteId($data, $inviteId);
        $message = '保存成功';
        $success = new MessageBag([
            'title' => $message
        ]);
        return redirect("/admin/communityMcn/inviteMember/{$briefId}/index")->with(compact('success'));
    }

    public function saveScript($url)
    {
        return <<<SCRIPT
         $('#view').unbind('click').click(function(){
          var note_id = $('#note_id').val();
          if(note_id == null || note_id == undefined || note_id == ""){
            alert('请输入NoteId')
            return false
          }
          var url = '{$url}/tupian/' + note_id + '.html';
            layer.open({
                type: 2,
                title: '搜索结果',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['400px', '700px'],
                content: url,
            });
         });
        SCRIPT;
    }
}